using System.IO;
using System.Linq;

namespace Sustainalytics
{
    public static class StringExtensions
    {
        public delegate bool TryParse<T>(string input, out T value);

        public static T ParseOrDefault<T>(this string input, TryParse<T> tryParse)
            => input.ParseOrDefault(tryParse, default(T));

        public static T ParseOrDefault<T>(this string input, TryParse<T> tryParse, T defaultValue)
        {
            T value;
            return tryParse(input, out value) ? value : defaultValue;
        }

        private static readonly char[] IllegalCharacters = Path.GetInvalidFileNameChars().Union(Path.GetInvalidPathChars()).ToArray();

        public static string ReplaceIllegalCharacters(this string value, string newValue)
            => value != null ? string.Join(newValue, value.Split(IllegalCharacters)) : null;

        public static string StripIllegalCharacters(this string value)
            => value?.ReplaceIllegalCharacters("");

        public static string ToReportNameString(this string value)
            => value?.ReplaceIllegalCharacters("_").Replace(" ", "_");
    }
}
